package com.arryluo.xinim.comm.config;

import com.arryluo.xinim.comm.config.util.Const;
import com.arryluo.xinim.system.dao.UserMapper;
import com.arryluo.xinim.system.mode.Users;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


public class ShiroDbRealm extends AuthorizingRealm {
	@Autowired
	private UserMapper userMapper;


	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		Users user = userMapper.login(new Users(token.getUsername(),String.valueOf(token.getPassword())));
		if(user==null){
			throw new UnknownAccountException("账号或密码不正确");
		}
		Subject subject = SecurityUtils.getSubject();
		Session session= subject.getSession();
		session.setAttribute(Const.SESSION_USER,user);
		// 认证缓存信息
		return new SimpleAuthenticationInfo(user.getId(), user.getPwd().toCharArray(), getName());

	}

	/**
	 * 
	 * Shiro权限认证
	 * 
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		return null;
	}

}
